package com.abel.bigwater.dataserver.model.ewide

import com.abel.bigwater.data.BcdString
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature
import io.netty.buffer.Unpooled
import org.joda.time.DateTime
import org.junit.Assert
import org.junit.Test
import org.slf4j.LoggerFactory

class FrameRowTest {

    @Test
    fun parseBuf() {
        val buf = Unpooled.buffer().apply { writeBytes(BcdString.toByteArray(HEX_DEMO)) }
        val p = KmingPacket()
        Assert.assertTrue(p.parseBuf(buf))

        lgr.info(JSON.toJSONStringWithDateFormat(p, JSON.DEFFAULT_DATE_FORMAT, SerializerFeature.PrettyFormat))

        Assert.assertEquals(TermCodeType().apply {
            manuId = BcdString.fromBcdString("03")
            codeBcd = BcdString.fromBcdString("01000000")
        }, p.termCode)

        val data = p.data as TermSendData
        Assert.assertEquals(2, data.frameCount)
        Assert.assertEquals(1, data.frameIndex)
        Assert.assertEquals(1, data.rowCount?.toInt())
        Assert.assertEquals(3, data.channelCount?.toInt())

        Assert.assertEquals(1, data.channelDataList.size)
        val row = data.channelDataList[0]
        Assert.assertArrayEquals(arrayOf(KmingChannelType.PulseTotal1,
                KmingChannelType.Pressure1,
                KmingChannelType.PulseRevert1), row.channelList.toArray())
        Assert.assertArrayEquals(arrayOf(1234L, 56789L, 3456789L),
                row.dataList.toArray())
    }

    @Test
    fun pack() {
        val d = TermSendData().apply {
            frameCount = 2
            frameIndex = 1
            rowCount = 1
            channelCount = 3
            channelDataList = arrayListOf(FrameRow(3).also {
                it.startTime = DateTime(2019, 7, 1, 2, 3, 4).toDate()
                it.channelList = arrayListOf(KmingChannelType.PulseTotal1,
                        KmingChannelType.Pressure1,
                        KmingChannelType.PulseRevert1)
                it.dataList = arrayListOf(1234, 56789, 3456789)
            })
        }

        val p = KmingPacket().apply {
            termCode = TermCodeType().also {
                it.manuId = BcdString.fromBcdString("03")
                it.codeBcd = BcdString.fromBcdString("01000000")
            }

            deviceStatus = DeviceStatus().also {
                it.lowBattery10 = true
                it.magnet21 = true
                it.breakLine30 = true
            }

            frameNo = 1
            data = d
        }

        val buf = Unpooled.buffer().apply {
            p.pack(this)

            Assert.assertEquals(HEX_DEMO, BcdString.hexString(this).toUpperCase())
        }
    }

    companion object {
        const val HEX_DEMO = "5A55010000000301020101001D00710200010001032019070102030483D204000087D5DD00008D15BF34000D576A69"
        private val lgr = LoggerFactory.getLogger(TermShutdownDataTest::class.java)
    }
}